﻿using System;

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Internal;

namespace Jack.EntityFrameworkCore
{
    public static class DbContextGetter
    {
        public static DbContext GetDbContext<T>(this DbSet<T> dbSet) where T : class
        {
            var infrastructure = dbSet as IInfrastructure<IServiceProvider>;
            var serviceProvider = infrastructure.Instance;
            var currentDbContext = serviceProvider.GetService(typeof(ICurrentDbContext))
                                       as ICurrentDbContext;
            return currentDbContext.Context;
        }
    }
}

// https://dev.to/j_sakamoto/how-to-get-a-dbcontext-from-a-dbset-in-entityframework-core-c6m

// How to use:
// 
// class MyDbContext {
//    public DbSet<FooBar> FooBar { get; set; }
// }
// ...
// var myContext = new MyDbContext();
// var contextFromDbSet = myContext.FooBar.GetDbContext();
//                                         ~~~~~~~~~~~~~~
// myContext == contextFromDbSet; // -> true
